﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.BL;
using Web.Models;

namespace Web.Controllers
{
    [Authorize]
    public class MessageController : Controller
    {
        //
        // GET: /Message/
        DataModelContainer db = new DataModelContainer();
        Service service = new Service(); 

        public ActionResult Index()
        {
            return RedirectToAction("Inbox");
        }

        public ActionResult Inbox()
        {
            UserRepresentation userrep = (UserRepresentation) Session["userrep"];
            int id = userrep.GetId();

            var model = service.GetRecievedMessagesForUser(userrep);

            return View(model);
        }

        [HttpPost]
        public ActionResult Inbox(IEnumerable<Message> lista)
        {
            return View(lista);
        }


        [HttpPost]
        public ActionResult SortBySender()
        {
            UserRepresentation userrep = (UserRepresentation)Session["userrep"];
            int id = userrep.GetId();

            var model = service.GetRecievedMessagesForUser(userrep).OrderBy(l => l.Usersender.name);

            return PartialView("_Message", model);
        }

        [HttpPost]
        public ActionResult SortByTitle()
        {
            UserRepresentation userrep = (UserRepresentation)Session["userrep"];
            int id = userrep.GetId();

            var model = service.GetRecievedMessagesForUser(userrep).OrderBy(l => l.title);

            return PartialView("_Message", model);
        }
        
        [HttpGet]
        public ActionResult SendMessage()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Details(int id)
        {

            Message message = service.getMessageById(id);
            if (message != null)
            {
                message.opened = true;
                db.SaveChanges();
                return View(message);
            }
            else
            {
                return Index();
            }
        }

        public ActionResult Archive()
        {
            UserRepresentation userrep = (UserRepresentation) Session["userrep"];

            var model = service.GetArchivedMessagesForUser(userrep);

            return View(model);
        }

        public ActionResult Outbox()
        {
            UserRepresentation userrep = (UserRepresentation)Session["userrep"];

            var model = service.GetSentMessagesForUser(userrep);

            return View(model);
        }

        public ActionResult Archivate(int id)
        {
            service.ArchivateMessage(id);

            return RedirectToAction("Inbox");
        }

        public ActionResult Delete(int id)
        {

            if (service.DeleteMessage(id))
            {
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        //TODO fixa så¨spara fungerar
        [HttpPost]
        public ActionResult SendMessage(FormCollection formdata)
        {
            var listOfUserRecipients = new List<string>(formdata["userRecipients"].ToString().Split(new Char [] {';',' '}));
            string userList = formdata["userRecipients"].ToString();
            var listOfGroupRecipients = new List<string>(formdata["groupRecipients"].ToString().Split(new Char [] {';',' '}));
            string groupList = formdata["groupRecipients"].ToString();
            UserRepresentation userrep = (UserRepresentation)Session["userrep"];
            int id = userrep.GetId();
            User sender = db.User.Single(u => u.id == id);
            var listOfAllRecipents = new List<User>();


            
            foreach(string temprecipient in listOfUserRecipients){

                string recipient = temprecipient.Trim();

                User user = db.User.SingleOrDefault(u => u.name.Equals(recipient)); //service.GetUser(recipient);
              
                if(user!= null){
                    listOfAllRecipents.Add(user);
                }

            }

            foreach(string temprecipient in listOfGroupRecipients){
                string recipient = temprecipient.Trim();

                Crew group = db.Crew.SingleOrDefault(g => g.name.Equals(recipient));

                if(group!= null){
                    var users = group.members;
                    foreach(User user in users){
                        listOfAllRecipents.Add(user);
                    }
                }
            }

            foreach (User user in listOfAllRecipents)
            {
                Message message = new Message();
                message.archived = false;
                message.deleted = false;
                message.title = formdata["title"].ToString();
                message.text = formdata["message"].ToString();
                message.timesent = DateTime.Now;
                message.opened = false;
                message.Userreceiver = user;
                message.Usersender = sender;

                db.Message.Add(message);
                //service.AddMessage(message);
                
            }

            int num = db.SaveChanges();

            

            return Index();
        }

    }
}
